define(["angularAMD"], function (angularAMD) {
    angularAMD.service('QT06_DownloadService', ['$state','$rootScope', '$filter', '$stateParams', 'config', '$mdDialog', 'MMWService', '$timeout',
        function ($state, $rootScope, $filter, $stateParams, config, $mdDialog, $MMWService, $timeout) {

            this.init = function(option, call_back){
                openDialog(option, call_back);
            };

            function openDialog(option, call_back) {
                $mdDialog.dialog(
                    "module/moduleQT/program/QT06/dialog/QT06_DownloadService.html",
                    function (dialog) {
                        return {
                            css_url: "module/moduleQT/program/QT06/QT06.css",
                            traceNameList: [],
                            checkNo: '',
                            async beforeShown() {
                                // 20220721 modify by Alan for#113392 : 修正excel下載檔名
                                if(option.checkNo != 'N/A' || option.checkNo != '') {
                                    dialog.checkNo = option.checkNo;
                                }
                                const resp = await getTraceNameList(option.modelName);
                                if(resp.TRACENAMEList && resp.TRACENAMEList.length > 0) {
                                    $timeout(() => {
                                        dialog.traceNameList = resp.TRACENAMEList;
                                        dialog.traceNameList.forEach((item) => {
                                            item.isSelect = false;
                                        });
                                    });
                                }
                            },
                            init() {},
                            back() {
                                dialog.hide();
                            },
                            async confirm() {
                                if (dialog.isDisabled()) return;

                                const selectedTraceList = $filter('filter')(dialog.traceNameList, { isSelect: true });
                                selectedTraceList.forEach((item) => {
                                    item.TRACENO = item.MODELSHEET;
                                })
                                const requestTraceList = selectedTraceList.map((item) => {
                                    item.TRACENO = item.MODELSHEET;
                                    return item;
                                })

                                if (window.nodeRequire) {
                                    // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                                    const { remote } = window.nodeRequire('electron');
                                    if(remote) {
                                        remote.dialog.showOpenDialog({
                                            properties: ['openDirectory']
                                        }, async (fileList) => {
                                            if (fileList && fileList.length > 0) {
                                                const resp = await getExcel(requestTraceList, option.modelName, option.checkNo);
                                                if (resp.ExcelFile) {
                                                    var file_data = Buffer.from(resp.ExcelFile, "base64");
                                                    // 20220721 modify by Alan for#113392 : 修正檔案命名方式
                                                    var file_name = `${fileList[0]}\\TRACEDATA_${moment().format(
                                                        "YYYYMMDDHHmmss"
                                                    )}.xls`;
                                                    window
                                                        .nodeRequire("fs")
                                                        .writeFile(file_name, file_data, function (error) {
                                                            if (error) {
                                                                $rootScope.showAlert(
                                                                    $filter("translate")(
                                                                        "common.msg.cantDownloadFile"
                                                                    ) + error
                                                                );
                                                            } else {
                                                                $rootScope.showConfirm(
                                                                    $filter("translate")(
                                                                        "common.msg.file_download_complete_and_open"
                                                                    ),
                                                                    function (dialog) {
                                                                        dialog.hide();
                                                                        // 20230807 modify by Alan for#130433 : electron升版後，shell.openItem改成shell.openPath
                                                                        const { shell } = window.nodeRequire('electron');
                                                                        shell.openItem ? shell.openItem(file_name) : shell.openPath(file_name);
                                                                    }
                                                                );
                                                            }
                                                        });
                                                }
                                            }
                                        });
                                    } else {
                                        const remote = window.nodeRequire('@electron/remote');
                                        remote.dialog.showOpenDialog({
                                            properties: ['openDirectory']
                                        }).then(async (result) => {
                                            if (result.filePaths && result.filePaths.length > 0) {
                                                const resp = await getExcel(requestTraceList, option.modelName, option.checkNo);
                                                if (resp.ExcelFile) {
                                                    var file_data = Buffer.from(resp.ExcelFile, "base64");
                                                    // 20220721 modify by Alan for#113392 : 修正檔案命名方式
                                                    var file_name = `${result.filePaths[0]}\\TRACEDATA_${moment().format(
                                                        "YYYYMMDDHHmmss"
                                                    )}.xls`;
                                                    window
                                                        .nodeRequire("fs")
                                                        .writeFile(file_name, file_data, function (error) {
                                                            if (error) {
                                                                $rootScope.showAlert(
                                                                    $filter("translate")(
                                                                        "common.msg.cantDownloadFile"
                                                                    ) + error
                                                                );
                                                            } else {
                                                                $rootScope.showConfirm(
                                                                    $filter("translate")(
                                                                        "common.msg.file_download_complete_and_open"
                                                                    ),
                                                                    function (dialog) {
                                                                        dialog.hide();
                                                                        // 20230807 modify by Alan for#130433 : electron升版後，shell.openItem改成shell.openPath
                                                                        const { shell } = window.nodeRequire('electron');
                                                                        shell.openItem ? shell.openItem(file_name) : shell.openPath(file_name);
                                                                    }
                                                                );
                                                            }
                                                        });
                                                }
                                            }
                                        });
                                    }
                                }
                                dialog.traceNameList.forEach((element) => {
                                    element.isSelect = false;
                                });
                                dialog.hide();
                            },
                            selectAll() {
                                const bool = !dialog.isSelectAll();
                                dialog.traceNameList.forEach((element) => {
                                    element.isSelect = bool;
                                });
                            },
                            isSelectAll() {
                                return (
                                    $filter("filter")(dialog.traceNameList, { isSelect: true }).length === dialog.traceNameList.length
                                );
                            },
                            isDisabled() {
                                return (
                                    $filter("filter")(dialog.traceNameList, { isSelect: true }).length <= 0
                                );
                            },
                        };
                    }
                );
            };  
            
            const service_QTP_Step3 =  (content) => {
                return new Promise(async (resolve, reject) => {
                    let result;
                    $MMWService.sendToServer({
                        uri: "ServicesSTD.Module_LEAN.QTP_Step3",
                        content: content,
                        success: (data) => (result = resolve(data)),
                    }, true);

                    return result;
                });
            };

            const getTraceNameList = async (modelName) => {
                const content = { Name: "GetVisibleTrace", ModelName: modelName };
                const resp = await service_QTP_Step3(content);
                return resp;
            };

            const getExcel = async (data, modelName, checkNo) => {
                const content = {
                    Name: "GetTraceForExcel",
                    Data: data,
                    ModelName: modelName,
                    NO: checkNo,
                };
                const resp = await service_QTP_Step3(content);
                return resp;
            };
        }
    ])
});
